# 写唤醒之后的处理逻辑
import src.record.recordController as rc
import src.record.BaiDuApiAudioToText as att
import src.record.BaiDuApiNPL as npl
from src.ResStatus import ResStatus
from src.logic.file_logic import find_word,delete_file,is_file_exist
from src.snowboy.snowboydecoder import play_audio_file

class SnowboyController:
    def __init__(self,config,log,mqtt,led):
        self.config = config
        self.log = log
        self.mqtt = mqtt
        self.led = led

    # 关键词检索开灯关灯
    def led_audio_control(self, words):
        try:
            # 读取配置文件关键词
            ledOnkeywords = self.config['aduio']['keywords']['ledon']
            ledOffkeywords = self.config['aduio']['keywords']['ledoff']
            # 关键词匹配
            if find_word(words, ledOnkeywords):
                self.led.on()
                self.log.info(ResStatus.LED_ON_SUCCESS)
                self.mqtt.client.publish(self.led.config['topic']['lednews'], ResStatus.LED_ON_SUCCESS.message)
                return True
            elif find_word(words, ledOffkeywords):
                self.led.off()
                self.log.info(ResStatus.LED_OFF_SUCCESS)
                self.mqtt.client.publish(self.led.config['topic']['lednews'], ResStatus.LED_OFF_SUCCESS.message)
                return True
            else:
                return False
        except Exception as e:
            raise e


def snowboy_callback(log,config,mqtt,led):
    try:
        log.info("智能语音唤醒成功")
        # 呼应
        play_audio_file(config['snowboy']['respFile'])
        # 进行录音操作（语音活动检测（VAD）没有实现，此项目使用固定录音时长
        if not rc.record_audio(log,config['aduio']['temp_file'],
                               record_seconds=config['aduio']['config']['seconds'],
                               channels=config['aduio']['config']['channels'],
                               chunk=config['aduio']['config']['chunk'],
                               sample_rate=config['aduio']['config']['rate']) or not is_file_exist(config['aduio']['temp_file']):
            log.info("请重新唤醒")
            return
        # 调用Api语音转文本
        attClass = att.BaiDuApiAudioToText(
            config=config,audioFile=config['aduio']['temp_file'],
            file_type=config['baidu_api']['file']['type'],rate=config['baidu_api']['file']['rate'])
        adText = attClass.get_result_FastApi()
        log.info("我说：{}".format(adText))
        # 调用Api进行词性分析
        nplClass = npl.BaiDuApiNPL(config=config)
        words = nplClass.get_WordSeg(adText)
        # 进行处理
        snowboyController = SnowboyController(config=config,log=log,mqtt=mqtt,led=led)
        result = snowboyController.led_audio_control(words)
        # 回应
        if result:
            play_audio_file(config['snowboy']['finishFile'])
        else:
            play_audio_file(config['snowboy']['errorFile'])
        # 删除临时文件
        delete_file(config['aduio']['temp_file'])
    except Exception as e:
        log.error("智能语音出错：{}".format(e))
    finally:
        log.info("等待继续唤醒....")
